class Mobile::Weixin::OrdersController < Mobile::Weixin::WeixinController
 include PrintOrder
 
    def index
        @orders = @current_user.orders.where(restaurant_id: @restaurant.id).order("created_at desc")
    end    

    def new_order
        render layout: false
        # @car = Car.find_or_create_by(user_id: @current_user.id,restaurant_id:@restaurant.id) 
    end    

    def cancel
        redirect_to "/mobile/weixin/welcome/#{@restaurant.id}/0"
    end

    def cancel_pay
        @order = Order.find_by_order_number params[:order_number]
        @car = Car.find_or_create_by(user_id: @current_user.id,restaurant_id:@restaurant.id)
        @car.add_line_item_from_order(@order)
        @order.destroy    
        redirect_to action: :new_order,format: :html
    end    
    
    def finish
        redirect_to "/mobile/weixin/welcome/#{@restaurant.id}/0"
    end   

    def wx_pay
        @order = Order.find params[:id]
        pay_result = wx_pay_params
        Rails.logger.debug(pay_result)
        @js_sign_params = wx_pay_sign pay_result        
    end    

    def new
        pay_type = params[:pay_type]
        @car = Car.find_or_create_by(user_id: @current_user.id,restaurant_id:@restaurant.id)
        @order = Order.new
        @order.user_id = @current_user.id
        @order.restaurant_id = @restaurant.id
        @order.table_no = @car.current_table_no
        @order.add_line_item_from_cart @car
        @order.pay_type = pay_type.to_i
        @order.save
        if @order.pay_type == Order::ONLINE_PAY
            redirect_to action: :wx_pay,id: @order.id,restaurant_id: @restaurant.id and return
        end    
    end    

    def show
        @order = Order.find params[:id]
    end  

    private
    def wx_pay_params
        pay_params = {
            body: "#{@order.restaurant.name}-微信支付",
            out_trade_no: @order.order_number,
            total_fee: @order.total_price.to_i*1,
            notify_url: 'http://weixin.beautyallin.com/notify/pay',
            spbill_create_ip: '47.90.8.33',
            trade_type: 'JSAPI',
            openid: @current_user.open_id
        }
        WxPay::Service.invoke_unifiedorder pay_params
    end 

    def wx_pay_sign pay_result
        sign_params = { 
            appId: WxPay.appid,
            timeStamp: Time.now.to_i,
            nonceStr: SecureRandom.uuid.tr('-', ''),
            package: "prepay_id=#{pay_result["prepay_id"]}",
            signType: 'MD5'
        }
        sign = WxPay::Sign.generate(sign_params)
        sign_params[:paySign] = sign
        return sign_params

    end   

   

end
